class Map < ActiveRecord::Base
  validates_numericality_of :x, :y, :zoom

  def Map.default
    Map.new(:zoom => 15, :x => -22.721050784598734, :y => -43.272013664245605)
  end
  
  def Map.first
    Map.find(:first, :order => 'id', :limit => 1)
  end
  
  def Map.last
    Map.find(:first, :order => 'id DESC', :limit => 1)
  end

  def previous
    check(self)
    Map.find(:first, :conditions => "id < #{id}", 
             :order => 'id DESC', :limit => 1)
  end
  
  def next
    check(self)
    Map.find(:first, :conditions => "id > #{id}", 
             :order => 'id', :limit => 1)
  end
  
  def moved_to(attrs)
    check(self)
    new_map = Map.new(attrs)
    unless new_map.coordinates == self.coordinates
      Map.delete_all("id > #{id}")
      new_map.save
      new_map
    else
      self
    end
  end
  
  def coordinates
    [ self.x, self.y, self.zoom ]
  end

  def first?
    self == Map.first
  end
  
  def last?
    self == Map.last
  end
  
  def location
    @location ||= Location.find(:first, 
                                :conditions => { :x => x, :y => y, :zoom => zoom})
  end
  
  def check(map)
    raise "Can't be nil or unsaved: #{map}" if map.nil? || map.new_record?
  end
end
